﻿using HZH_Controls.Controls;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using 渐变.common;

namespace 渐变.user_Form
{
    public partial class no_paymentForm : Form
    {
        public no_paymentForm()
        {
            InitializeComponent();
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {

        }
        public void loadMsg()
        {
            List<DataGridViewColumnEntity> lstCulumns = new List<DataGridViewColumnEntity>();
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "RentID", HeadText = "订单编号", Width = 20, WidthType = SizeType.AutoSize });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "price", HeadText = "应付金额", Width = 20, WidthType = SizeType.AutoSize });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "carname", HeadText = "车名", Width = 50, WidthType = SizeType.AutoSize });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "CNumber", HeadText = "车牌号", Width = 20, WidthType = SizeType.AutoSize });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "opername", HeadText = "租车人", Width = 20, WidthType = SizeType.AutoSize });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "begindate", HeadText = "起始时间", Width = 20, WidthType = SizeType.Percent });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "returntime", HeadText = "归还时间", Width = 20, WidthType = SizeType.Percent });
            this.ucDataGridView1.Columns = lstCulumns;
            this.ucDataGridView1.IsShowCheckBox = true;
            List<object> lstSource = new List<object>();
            string sql = "select * from carRents where opername=@opername and isPay='False'";
            SqlParameter p = new SqlParameter("@opername", this.opname);
            DataTable dt = new DataTable();
            dt = DBHelper.ExecuteQuery(sql, p);
            this.ucDataGridView1.DataSource = dt;
            this.ucDataGridView1.First();
        }
        public string opname { get; set; }
        private void ucDataGridView1_Load(object sender, EventArgs e)
        {
            loadMsg();


        }

        private void no_paymentForm_Load(object sender, EventArgs e)
        {

            this.Dock = DockStyle.Fill;
        }

        private void ucDataGridView1_ItemClick(object sender, DataGridViewEventArgs e)
        {
            string id = (ucDataGridView1.Rows[0].DataSource as DataRow)["RentID"].ToString();
            Console.WriteLine(id);
            
        }

        private void ucDataGridView1_Click(object sender, EventArgs e)
        {
            
        }

        private void btnPay_Click(object sender, EventArgs e)
        {

            if (ucDataGridView1.SelectRows != null && ucDataGridView1.SelectRows.Count > 0)
            {
                var uids = new List<int>();
                var carids = new List<string>();
                foreach (var item in ucDataGridView1.SelectRows)
                {
                    var tempid = Convert.ToInt32((item.DataSource as DataRow)["RentID"]);
                    var numberId = (item.DataSource as DataRow)["CNumber"].ToString();
                    uids.Add(tempid);
                    carids.Add(numberId);
                }
                DialogResult dir = MessageBox.Show("您确定要支付吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                if (dir == DialogResult.OK)
                {
                    var uidsstr = new StringBuilder();
                    uidsstr.Append("(");
                    foreach (var item in uids)
                    {
                        uidsstr.Append($"{item},");
                    }
                    uidsstr.Remove(uidsstr.Length - 1, 1);
                    uidsstr.Append(")");



                    var uidsstr2 = new StringBuilder();
                    uidsstr2.Append("(");
                    foreach (var item in carids)
                    {
                        uidsstr2.Append($"'{item}',");
                    }
                    uidsstr2.Remove(uidsstr2.Length - 1, 1);
                    uidsstr2.Append(")");
                    //求出总价格
                    string sql = $"select sum(price) from carRents where RentId IN {uidsstr};";
                    string sum = DBHelper.ExecuteScalar(sql).ToString();

                    string sql3 = "select umoney from uUser where uUsername=@uUsername";
                    SqlParameter p = new SqlParameter("@uUsername", opname);
                    DataTable dt = new DataTable();
                    dt = DBHelper.ExecuteQuery(sql3, p);
                    //获得余额
                    string Mon = dt.Rows[0][0].ToString();
                    //拿余额与需要支付的金额进行比较
                    if (Convert.ToDecimal(Mon) >= Convert.ToDecimal(sum))
                    {
                        //余额支付
                        string id = (ucDataGridView1.SelectRow.DataSource as DataRow)["RentID"].ToString();
                        string opername = (ucDataGridView1.SelectRow.DataSource as DataRow)["opername"].ToString();
                        string sql9 = "update uUser set umoney = umoney-@price where uUsername=@uUsername";
                        SqlParameter[] ps =
                        {
                new SqlParameter("@price",sum),
                new SqlParameter("@uUsername",opername)
            };
                        int result = DBHelper.ExecuteNonQuery(sql9, ps);
                        if (result > 0)
                        {
                            //支付成功，扣掉余额,修改支付状态
                            this.ShowSuccessTip("支付成功！欢迎下次使用！");
                            string sql2 = $"update carRents set isPay='True',Paytime='{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' where RentId in {uidsstr}";
                           // string sql2 = $"update carRents set isPay='True',Paytime=DateTime.Now where RentId in {uidsstr};";
            //                SqlParameter[] ps2 =
            //                {
            //        new SqlParameter("@RentId",uidsstr),
            //        new SqlParameter("@Paytime",DateTime.Now)
            //};
                            DBHelper.ExecuteNonQuery(sql2);
                            //支付成功   销售表如果存在，此类型则count+1  
                            //uidsstr2 为选中的所有的车牌号
                            string a1 = $"select CTypeId from CarInfo where CNumber in {uidsstr2}";
                            // SqlParameter p1 = new SqlParameter("@CNumber", (ucDataGridView1.SelectRow.DataSource as DataRow)["CNumber"].ToString());
                            DataTable d1 = DBHelper.ExecuteQuery(a1);

                            ModelHandler<model.carInfo> modelconvert = new ModelHandler<model.carInfo>();
                            var list = modelconvert.FillModel(d1);
                            var str = new StringBuilder();
                            str.Append($"(");
                            foreach (var item in list)
                            {
                                
                                str.Append($"{item.CTypeId},");
                            }
                            str.Remove(str.Length - 1, 1);
                            str.Append($")");
                            //nb  

                            string a2 = $"update Sale set Scount=Scount+1 where CTypeId in {str}";
                            //SqlParameter p2 = new SqlParameter("@CTypeId", CTypeId);
                            DBHelper.ExecuteNonQuery(a2);
                            //不存在，则新增一条数据
                            loadMsg();


                        }
                    }
                    else
                    {
                        this.ShowErrorDialog("余额不足!请充值！");
                    }
                }
                else
                {
                    return;
                }
            }
            else
            {
                this.ShowErrorTip("未选择任何车辆，请选择要支付的车辆再进行支付!");
            }
           

        }
      

        //        //点击支付，默认使用余额扣款，
        //        DialogResult dir = MessageBox.Show("您确定使用余额支付吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
        //        if (dir == DialogResult.OK)
        //        {
        //            string sql3 = "select umoney from uUser where uUsername=@uUsername";
        //        SqlParameter p = new SqlParameter("@uUsername", opname);
        //        DataTable dt = new DataTable();
        //        dt = DBHelper.ExecuteQuery(sql3, p);
        //            //获得余额
        //            string Mon = dt.Rows[0][0].ToString();
        //        //待支付金额
        //        string price = (ucDataGridView1.SelectRow.DataSource as DataRow)["price"].ToString();
        //            //拿余额与需要支付的金额进行比较
        //            if (Convert.ToDecimal(Mon) >= Convert.ToDecimal(price))
        //            {
        //                //余额支付
        //                string id = (ucDataGridView1.SelectRow.DataSource as DataRow)["RentID"].ToString();
        //        string opername = (ucDataGridView1.SelectRow.DataSource as DataRow)["opername"].ToString();
        //        string sql = "update uUser set umoney = umoney-@price where uUsername=@uUsername";
        //        SqlParameter[] ps =
        //        {
        //                new SqlParameter("@price",price),
        //                new SqlParameter("@uUsername",opername)
        //            };
        //        int result = DBHelper.ExecuteNonQuery(sql, ps);
        //                if (result > 0)
        //                {
        //                    //支付成功，扣掉余额,修改支付状态
        //                    this.ShowSuccessTip("支付成功！欢迎下次使用！");
        //        string sql2 = "update carRents set isPay='True',Paytime=@Paytime where RentId = @RentId";
        //        SqlParameter[] ps2 =
        //        {
        //                    new SqlParameter("@RentId",id),
        //                    new SqlParameter("@Paytime",DateTime.Now)
        //            };
        //        DBHelper.ExecuteNonQuery(sql2, ps2);
        //                    //支付成功   销售表如果存在，此类型则count+1
        //                    string a1 = "select CTypeId from CarInfo where CNumber = @CNumber";
        //        SqlParameter p1 = new SqlParameter("@CNumber", (ucDataGridView1.SelectRow.DataSource as DataRow)["CNumber"].ToString());
        //        DataTable d1 = new DataTable();
        //        d1 = DBHelper.ExecuteQuery(a1, p1);
        //                    string CTypeId = d1.Rows[0][0].ToString();

        //        string a2 = "update Sale set Scount=Scount+1 where CTypeId = @CTypeId";
        //        SqlParameter p2 = new SqlParameter("@CTypeId", CTypeId);
        //        DBHelper.ExecuteNonQuery(a2, p2);
        //                    //不存在，则新增一条数据
        //                    loadMsg();


        //    }
        //}


        //            else
        //{
        //    this.ShowErrorDialog("余额不足!请充值！");
        //}
        //        }
        //        else
        //{
        //    return;
        //}
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (ucDataGridView1.SelectRows != null && ucDataGridView1.SelectRows.Count > 0)
            {
                var uids = new List<int>();
                var carbumber = new List<string>();
                foreach (var item in ucDataGridView1.SelectRows)
                {
                    var tempid = Convert.ToInt32((item.DataSource as DataRow)["RentID"]);
                    var number = (item.DataSource as DataRow)["CNumber"].ToString();
                    uids.Add(tempid);
                    carbumber.Add(number);
                }
                DialogResult dir = MessageBox.Show("您确定要取消订单吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                if (dir == DialogResult.OK)
                {
                    var uidsstr = new StringBuilder();
                    uidsstr.Append("(");
                    foreach (var item in uids)
                    {
                        uidsstr.Append($"{item},");
                    }
                    uidsstr.Remove(uidsstr.Length - 1, 1);
                    uidsstr.Append(")");


                    var uidsstr2 = new StringBuilder();
                    uidsstr2.Append("(");
                    foreach (var item in carbumber)
                    {
                        uidsstr2.Append($"'{item}',");
                    }
                    uidsstr2.Remove(uidsstr2.Length - 1, 1);
                    uidsstr2.Append(")");


                    string sql = $"delete from carRents where RentID in {uidsstr};";
                    int result = DBHelper.ExecuteNonQuery(sql);
                    if (result > 0)
                    {
                        this.ShowSuccessTip("取消成功！");
                        //修改汽车的状态为空闲
                        string sql2 = $"update CarInfo set CStatus = 'True' where CNumber in {uidsstr2}";
                        DBHelper.ExecuteNonQuery(sql2);
                        this.DialogResult = DialogResult.OK;
                        loadMsg();
                    }
                    else
                    {
                        this.ShowErrorTip("取消失败！");
                    }
                }
                else
                {
                    return;
                }
            }
            else
            {
                this.ShowErrorTip("未选择任何订单，请选择订单后再进行取消!");
            }

            //DialogResult dir = MessageBox.Show("您确定要取消订单吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            //if (dir == DialogResult.OK)
            //{
            //    string id = (ucDataGridView1.SelectRow.DataSource as DataRow)["RentID"].ToString();

            //    string sql = "delete from carRents where RentID=@RentID";
            //    SqlParameter[] ps =
            //    {
            //        new SqlParameter("@RentID",id),

            //    };
            //    int result = DBHelper.ExecuteNonQuery(sql, ps);
            //    if (result > 0)
            //    {

            //        this.ShowSuccessTip("取消成功！");
            //        //修改汽车的状态为空闲
            //        string sql2 = "update CarInfo set CStatus = 'True' where CNumber=@CNumber";
            //        SqlParameter p = new SqlParameter("@CNumber", (ucDataGridView1.SelectRow.DataSource as DataRow)["CNumber"].ToString());
            //        DBHelper.ExecuteNonQuery(sql2, p);
            //        this.DialogResult = DialogResult.OK;
            //        loadMsg();


            //    }
            //    else
            //    {
            //        this.ShowErrorTip("取消失败！");
            //    }
            //}
            //else
            //{
            //    return;
            //}
        }
    }
}
